var _ = require("underscore");
var Movie = require("../models/movie");
var Catgory = require("../models/catgory");
var Comment = require("../models/comment");
var fs = require('fs');
var path = require('path');


// 详情页
exports.detail = function (req, res) {
    var id = req.params.id;

    Movie.findById(id, function (err, movie) {
        // 方案一
        // Comment.find({ movie: id }, function (err, comments) {
        //     // console.log(comments)
        //     if (movie) {
        //         res.render("detail", {
        //             title: "详情页 -- " + movie.title,
        //             movie: movie,
        //             comments: comments
        //         });
        //     } 
        // })
        // 方案二
        Comment
        .find({ movie: id })
        .populate('from', 'name')
        .populate('reply.from reply.to', 'name')
        .exec(function (err, comments) {
            console.log(comments)
            if (movie) {
                res.render("detail", {
                    title: "详情页 -- " + movie.title,
                    movie: movie,
                    comments: comments
                });
            } 
        })
        // if (err) {
        //     console.log(err);
        // }
        
    });
}
// 后台录入页
exports.new =  function (req, res) {
    Catgory.find({},function (err,catgories) {  
        res.render("admin", {
            title: "后台录入页",
            catgories: catgories,
            movie: {}
        });
    })  
}
// 更新电影
exports.update = function (req, res) {
    var id = req.params.id;
    if (id) {
        Movie.findById(id, function (err, movie) {
            Catgory.find({},function (err,catgories) { 
                res.render("admin", {
                    title: "后台更新页",
                    catgories: catgories,
                    movie: movie
                });
            });
        })
    }
}

// 上传海报
exports.savePoster = function (req, res, next) {  
    console.log(req.files)
    var posterData = req.files.uploadPoster;
    var filePath = posterData.path;
    var originalFilename = posterData.originalFilename;

    if(originalFilename){ // 有文件上传 
        fs.readFile(filePath, function (err, data) {  
            var timestamp = Data.now()
            var type = posterData.type.split('/')[1];
            var poster = timestamp + '.' + type;
            var newPath = path.join(__dirname, '../../' , '/public/upload' + poster);
            fs.writeFile(newPath, data , function (err) {  
                req.poster = poster;
                next ();
            })
        })
    }else{
        next ()
    }
}

// 修改或添加电影
exports.save = function (req, res) {
    var id = req.body.movie._id;
    var movieObj = req.body.movie;
    var _movie;

    if(req.poster){
        movieObj.poster = req.poster;
    }

    if (id) { // 修改
        Movie.findById(id, function (err, movie) {
            if (err) {
                console.log(err);
            }
            _movie = _.extend(movie, movieObj);
            _movie.save(function (err, movie) {
                if (err) {
                    console.log(err);
                }
                res.redirect("/movie/" + movie._id);
            });
        });
    } else { // 新加  
        _movie = new Movie(movieObj);
        var CatgoryId = movieObj.catgory;
        var CatgoryName = movieObj.catgoryName;
        _movie.save(function (err, movie) {
            if (err) {
                console.log(err);
            }
            if(CatgoryId){
                // 把数据库中分类的movies push进新加的电影id
                Catgory.findById(CatgoryId,function(err,catgory){
                    catgory.movies.push(_movie._id)
                    catgory.save(function(err,catgory){
                        res.redirect("/movie/" + movie._id);
                    })
                })
            }else if(CatgoryName){ 
                var catgory = new Catgory({
                    name: CatgoryName,
                    movies:[movie._id]
                })
                catgory.save(function (err,catgory) { 
                    res.redirect("/movie/" + movie._id);
                })
            }
        });
    }
}
// 列表页
exports.list = function (req, res) {
    Movie.fetch(function (err, movies) {
        if (err) {
            throw err
        }
        res.render("list", {
            title: "列表页",
            movies: movies
        });
    });
}

// 删除
exports.del =  function (req, res) {
    var id = req.query.id;
    // return console.info(id);
    if (id) {
        Movie.remove({ _id: id }, function (err, movie) {
            if (err) {
                console.log(err)
            } else {
                res.json({ success: 1 })
            }
        })
    }
}